package com.yds.developtools.views

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.appcompat.widget.AppCompatTextView
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton
import com.yds.developtools.R
import com.yds.developtools.utils.YDSAppHelper
import com.yds.developtools.utils.YDSXutilsDownloadFileHelper
import com.yds.developtools.utils.YDSLogHelper
import com.yds.developtools.utils.YDSToastHelper.showShortToastCenter
import java.io.File

/**
 * 作者:     YDS
 * 创建时间: 2025/3/16 21:56
 * 页面描述: 升级提示框
 * val upgradeDialog = YDSUpgradeDialog(YDSActivityStackHelper.topActivity()!!) {}
 *     upgradeDialog.show()
 *     upgradeDialog.setUpgradeApkUrl(apkBean.url)
 *     upgradeDialog.setUpgradeTitle("升级版本：$versionName")
 *     upgradeDialog.setUpgradeContent("更新内容：\n${apkBean.content}")
 *     upgradeDialog.setUpgradeCancelable(false)
 *     upgradeDialog.setUpgradeCanceledOnTouchOutside(false)
 */
@Suppress("Unused")
class YDSUpgradeDialog : Dialog {
    private var context: Context
    private var apkUrl: String = ""
    private var layoutId: Int = -1

    // 存放apk文件得文件夹地址
    private var apkPath: String = "${Environment.getExternalStorageDirectory().absolutePath}/Download/"
    private var callback: () -> Unit

    constructor(context: Context, layoutId: Int = -1, callback: () -> Unit) : this(context, layoutId, R.style.normal_dialog, callback)

    constructor(context: Context, layoutId: Int, themeResId: Int, callback: () -> Unit) : super(context, themeResId) {
        this.context = context
        this.layoutId = layoutId
        this.callback = callback
    }

    private lateinit var mTvUpgradeTitle: AppCompatTextView
    private lateinit var mTvUpgradeContent: AppCompatTextView
    private lateinit var mPbApkFile: ProgressBar
    private lateinit var mBtnUpgrade: QMUIRoundButton

    @SuppressLint("InflateParams")
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val view = LayoutInflater.from(context).inflate(if (layoutId == -1) R.layout.dialog_yds_upgrade else layoutId, null)
        mTvUpgradeTitle = view.findViewById(R.id.mTvUpgradeTitle)
        mTvUpgradeContent = view.findViewById(R.id.mTvUpgradeContent)
        mPbApkFile = view.findViewById(R.id.mPbApkFile)
        mBtnUpgrade = view.findViewById(R.id.mBtnUpgrade)

        mBtnUpgrade.setOnClickListener {
            if (apkUrl.isEmpty()) {
                context.showShortToastCenter("APK文件地址错误！")
                return@setOnClickListener
            }
            YDSLogHelper.i("立即升级 $apkUrl $apkPath")
            downloadApkFile()
        }

        val window = checkNotNull(window)
        // 设置窗口背景为透明
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        // 去除默认的蒙层效果
//        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        // 消除边距
        window.decorView.setPadding(0, 0, 0, 0)
        // 设置窗口动画
        window.setWindowAnimations(R.style.AnimBottom)
        // 设置窗口显示的位置
        window.setGravity(Gravity.CENTER)
        // 设置窗口大小为 1 像素
        val layoutParams = window.attributes
        val displayMetrics = context.resources.displayMetrics
        layoutParams.width = (displayMetrics.widthPixels * 0.8).toInt()
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
        window.attributes = layoutParams
//        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(view)
    }

    /*** 作者: YDS 时间: 2025/4/18 10:53 描述: 是否按返回键消失 ***/
    fun setUpgradeCancelable(isCanCancel: Boolean) {
        setCancelable(isCanCancel)
    }

    /*** 作者: YDS 时间: 2025/4/18 10:53 描述: 是否触碰外部消失 ***/
    fun setUpgradeCanceledOnTouchOutside(isCanCancel: Boolean) {
        setCanceledOnTouchOutside(isCanCancel)
    }

    /*** 作者: YDS 时间: 2025/4/18 9:58 描述: 设置升级标题 ***/
    fun setUpgradeTitle(title: String) {
        mTvUpgradeTitle.text = title
    }

    /*** 作者: YDS 时间: 2025/4/18 9:58 描述: 设置升级内容 ***/
    fun setUpgradeContent(content: String) {
        mTvUpgradeContent.text = content
    }

    /*** 作者: YDS 时间: 2025/4/18 9:58 描述: 设置升级按钮文案 ***/
    fun setUpgradeButtonText(text: String) {
        mBtnUpgrade.text = text
    }

    /*** 作者: YDS 时间: 2025/4/18 10:15 描述: 设置升级apk文件下载地址 ***/
    fun setUpgradeApkUrl(apkUrl: String) {
        this.apkUrl = apkUrl
    }

    /*** 作者: YDS 时间: 2025/4/18 10:15 描述: 设置升级apk文件下载路径 ***/
    fun setUpgradeApkFilePath(apkPath: String) {
        this.apkPath = apkPath
    }

    /*** 作者: YDS 时间: 2025/4/18 10:15 描述: 下载apk文件 ***/
    private fun downloadApkFile() {
        mPbApkFile.visibility = View.VISIBLE
        YDSXutilsDownloadFileHelper.downloadFile(
            apkUrl, apkPath + YDSXutilsDownloadFileHelper.parseFileName(apkUrl),
            object : YDSXutilsDownloadFileHelper.CommonFileCallBack<String> {
                @SuppressLint("SetTextI18n")
                override fun onLoading(progress: Int) {
                    super.onLoading(progress)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        mPbApkFile.setProgress(progress, true)
                    } else {
                        mPbApkFile.progress = progress
                    }
                    mBtnUpgrade.isEnabled = false
                    mBtnUpgrade.text = "下载进度：$progress%"
                }

                override fun onSuccess(result: String) {
                    YDSLogHelper.i("下载完成：$result")
                    mBtnUpgrade.isEnabled = false
                    mBtnUpgrade.text = "下载完成"
                    YDSAppHelper.installApp(context, File(result))
                    dismiss()
                }

                override fun onError(errorMsg: String) {
                    super.onError(errorMsg)
                    YDSLogHelper.i("下载失败：$errorMsg")
                    mBtnUpgrade.isEnabled = true
                    mBtnUpgrade.text = "下载失败，请重试！"
                }

            })
    }

    override fun dismiss() {
        super.dismiss()
        callback()
    }

}
